package cn.tedu.blog.server.repo.impl;


import cn.tedu.blog.server.pojo.vo.CategoryListVO;
import cn.tedu.blog.server.repo.ICategoryRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Repository
public class CategoryRepository implements ICategoryRepository {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    @Override
    public boolean isExpired(String key) {
        Long expiredTime= redisTemplate.getExpire(key);
        log.debug("密钥有效时间：{}",expiredTime);
        if(expiredTime==-2){
            return true;
        }
        return false;
    }

    @Override
    public void putList(List<CategoryListVO> list, String key) {
        for (CategoryListVO categoryListVO : list) {
            redisTemplate.opsForList().rightPush(key, categoryListVO);
        }
        switch (key){
            case KEY_CATEGORY_LIST:
                redisTemplate.expire(key,1L, TimeUnit.DAYS);
                break;
        }

    }

    @Override
    public List<CategoryListVO> getList(String key) {
        log.debug("即将从Redis中读取分类列表数据……");
        List<Serializable> list = redisTemplate.opsForList().range(key, 0, -1);
        List<CategoryListVO> categoryList = new ArrayList<>();
        for (Serializable serializable : list) {
            categoryList.add((CategoryListVO) serializable);
            log.debug("从Redis中读取到的分类列表：{}", categoryList);
        }
        return categoryList;
    }


}
